package com.ibpd.henuocms.web.controller.manage;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ibpd.henuocms.assist.ExtUserRoleEntity;
import com.ibpd.henuocms.assist.PermissionModelEntity;
import com.ibpd.henuocms.common.IbpdLogger;
import com.ibpd.henuocms.common.SysUtil;
import com.ibpd.henuocms.entity.FunEntity;
import com.ibpd.henuocms.entity.NodeEntity;
import com.ibpd.henuocms.entity.RoleEntity;
import com.ibpd.henuocms.entity.RolePermissionEntity;
import com.ibpd.henuocms.entity.SubSiteEntity;
import com.ibpd.henuocms.entity.UserEntity;
import com.ibpd.henuocms.entity.UserRoleEntity;
import com.ibpd.henuocms.service.fun.FunServiceImpl;
import com.ibpd.henuocms.service.fun.IFunService;
import com.ibpd.henuocms.service.node.INodeService;
import com.ibpd.henuocms.service.node.NodeServiceImpl;
import com.ibpd.henuocms.service.role.IRolePermissionService;
import com.ibpd.henuocms.service.role.IRoleService;
import com.ibpd.henuocms.service.role.RolePermissionServiceImpl;
import com.ibpd.henuocms.service.role.RoleServiceImpl;
import com.ibpd.henuocms.service.subSite.ISubSiteService;
import com.ibpd.henuocms.service.subSite.SubSiteServiceImpl;
import com.ibpd.henuocms.service.user.IUserRoleService;
import com.ibpd.henuocms.service.user.IUserService;
import com.ibpd.henuocms.service.user.UserRoleServiceImpl;
import com.ibpd.henuocms.service.user.UserServiceImpl;

@Controller
public class Role extends BaseController {
	@RequestMapping("Manage/Role/index.do")
	public String index(org.springframework.ui.Model model,HttpServletRequest req) throws IOException{
		model.addAttribute(PAGE_TITLE,"角色管理");
		return "manage/role/index";
	}
	@RequestMapping("Manage/Role/toAdd.do")
	public String toAdd(Model model,HttpServletRequest req,HttpServletResponse resp) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		model.addAttribute(PAGE_TITLE,"添加角色");
		model.addAttribute("htmls",super.getHtmlString(null, "role.add.field"));
		return "manage/role/add";
	}
	@RequestMapping("Manage/Role/toEdit.do")
	public String toEdit(Model model,Long id,HttpServletRequest req,HttpServletResponse resp) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		model.addAttribute(PAGE_TITLE,"编辑角色");
		IRoleService rs=(IRoleService) getService(RoleServiceImpl.class);
		RoleEntity ce=rs.getEntityById(id);
		model.addAttribute("htmls",super.getHtmlString(ce, "role.edit.field"));
		model.addAttribute("entity",ce);
		return "manage/role/edit";
	}
	@RequestMapping("Manage/Role/doAdd.do")
	public void doAdd(RoleEntity role,HttpServletResponse resp) throws IOException{
		if(role==null){
			printParamErrorMsg(resp);
			return;
		}
		if(role.getName()==null || role.getName().trim().length()==0){
			super.printMsg(resp, "-2", "-1", "名称不能为空");
			return;
		}
		role.setOrder(role.getOrder()==null?0:role.getOrder());
		role.setRemark(StringUtils.isBlank(role.getRemark())?"没有备注":role.getRemark());
		IRoleService rs=(IRoleService) getService(RoleServiceImpl.class);
		rs.saveEntity(role);
		super.printMsg(resp, "1", "1", "保存成功");		
	}
	@RequestMapping("Manage/Role/doEdit.do")
	public void doEdit(RoleEntity role,HttpServletResponse resp) throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		if(role==null){
			printParamErrorMsg(resp);
			return;
		}
		if(role.getId()==null || role.getId()<=0){
			super.printMsg(resp, "-2", "-1", MSG_PARAMERROR_MSG);
			return;
		}
		if(role.getName()==null || role.getName().trim().length()==0){
			super.printMsg(resp, "-3", "-1", "名称不能为空");
			return;
		}
		role.setOrder(role.getOrder()==null?0:role.getOrder());
		role.setRemark(StringUtils.isBlank(role.getRemark())?"没有备注":role.getRemark());
		IRoleService rs=(IRoleService) getService(RoleServiceImpl.class);
		RoleEntity dbRole=rs.getEntityById(role.getId());
		super.swap(role, dbRole);
		rs.saveEntity(dbRole);
		super.printMsg(resp, "1", "1", "保存成功");
	}
	@RequestMapping("Manage/Role/doDel.do")
	public void doDel(String ids,HttpServletResponse resp) throws IOException{
		IRoleService rs=(IRoleService) getService(RoleServiceImpl.class);
		rs.batchDel(ids);
		super.printMsg(resp, "1", "1", "保存成功");
	}
	@RequestMapping("Manage/Role/list.do")
	public void getList(HttpServletRequest req,HttpServletResponse resp,String order,Integer page,Integer rows,String sort,String queryData){
		IRoleService roleService=(IRoleService)getService(RoleServiceImpl.class);
		super.getList(req, roleService, resp, order, page, rows, sort, queryData);
	}
	@RequestMapping("Manage/Role/props.do")
	public String props(Long id,Model model) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		if(id==null || id<0L){
			model.addAttribute(ERROR_MSG,MSG_PARAMERROR_MSG);
			return super.ERROR_PAGE;
		}
		IRoleService roleServ=(IRoleService) getService(RoleServiceImpl.class);
		RoleEntity ce=roleServ.getEntityById(id);
		if(ce==null){
			model.addAttribute(ERROR_MSG,"没有该角色");
			return super.ERROR_PAGE;
		}
		model.addAttribute(PAGE_TITLE,"参数设置");
		model.addAttribute("htmls",super.getHtmlString(ce, "role.edit.field"));
		model.addAttribute("entity",ce);
		return "manage/role/props";
	}	
	@RequestMapping("Manage/Role/saveProp.do")
	public void saveProps(Long id,String field,String value,HttpServletResponse resp) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException{
		if(id!=null && id!=-1){
			IRoleService roleServ=(IRoleService) getService(RoleServiceImpl.class);
			RoleEntity cata=roleServ.getEntityById(id);
				if(cata!=null){
					//先确定参数类型
					Method tmpMethod=cata.getClass().getMethod("get"+field.substring(0,1).toUpperCase()+field.substring(1), new Class[]{});
					
					
					Method method=cata.getClass().getMethod("set"+field.substring(0,1).toUpperCase()+field.substring(1), new Class[]{tmpMethod.getReturnType()});
					Object val=getValue(value,tmpMethod.getReturnType().getSimpleName());
					IbpdLogger.getLogger(this.getClass()).info("value="+val);
					method.invoke(cata, val);
					roleServ.saveEntity(cata);
//					roleServ.getDao().clearCache();
					super.printMsg(resp, "99", cata.getId().toString(), "保存成功");		
				}else{
					super.printMsg(resp, "-1", "", "没有该类别");
				}
		}else{
			printParamErrorMsg(resp);			
		}
	}
	@RequestMapping("Manage/Role/permissionConfig.do")
	public String permissionConfig(Model model,Long roleId,HttpServletRequest req,HttpServletResponse resp) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		model.addAttribute(PAGE_TITLE,"权限设置");
		IRoleService rs=(IRoleService) getService(RoleServiceImpl.class);
		RoleEntity ce=rs.getEntityById(roleId);
		if(ce==null){
			model.addAttribute(ERROR_MSG,"没有该角色");
			return super.ERROR_PAGE;
		}
		model.addAttribute("roleId",roleId);
		//把功能都检索出来
		IFunService funServ=(IFunService) getService(FunServiceImpl.class);
		List<FunEntity> funList=funServ.getList();
		//想把这些fun都 做一个分类，则重新分类一下
		Map<String,List<FunEntity>> funMap=new HashMap<String,List<FunEntity>>();
		if(funList!=null){
			for(FunEntity f:funList){
				List<FunEntity> fl=funMap.get(f.getFunGroup());
				fl=(fl==null)?new ArrayList<FunEntity>():fl;
				fl.add(f);
				funMap.put(f.getFunGroup(), fl);
			}
		}
		model.addAttribute("funMap",funMap);
		//下面把站点、栏目、模块等需要做权限控制的模块都集中起来
		ISubSiteService  siteServ=(ISubSiteService) getService(SubSiteServiceImpl.class);
		INodeService nodeServ=(INodeService) getService(NodeServiceImpl.class);
		List<SubSiteEntity> siteList=siteServ.getList();
		List<PermissionModelEntity> modelList=new ArrayList<PermissionModelEntity>();
		if(siteList!=null){
			for(SubSiteEntity site:siteList){
				PermissionModelEntity p=new PermissionModelEntity();
				p.setModelId(site.getId());
				p.setModelName(site.getSiteName());
				p.setModelType(PermissionModelEntity.MODEL_TYPE_SITE);
				modelList.add(p);
				List<NodeEntity> nodeList=nodeServ.getList("from "+nodeServ.getTableName()+" where subSiteId="+p.getModelId(), null);
				if(nodeList!=null){
					for(NodeEntity n:nodeList){
						PermissionModelEntity np=new PermissionModelEntity();
						np.setModelId(n.getId());
						np.setModelName(n.getText());
						np.setModelType(PermissionModelEntity.MODEL_TYPE_NODE);
						modelList.add(np);
					}
				}
				
			}
		}
		model.addAttribute("modelList",modelList);
		//把现有的 设置信息读取出来
		IRolePermissionService rpServ=(IRolePermissionService) getService(RolePermissionServiceImpl.class);
		List<RolePermissionEntity> rpList=rpServ.getListByRoleId(roleId);
		Map<String,Boolean> confMap=new HashMap<String,Boolean>();
		for(RolePermissionEntity r:rpList){
			confMap.put(r.getFunId()+"-"+r.getModelId()+"-"+r.getTypeId(), true);
			IbpdLogger.getLogger(this.getClass()).info(r.getFunId()+"-"+r.getModelId()+"-"+r.getTypeId());
		}
		model.addAttribute("confMap",confMap);
		return "manage/role/permissionConfig";
	}
	@RequestMapping("Manage/Role/userConfig.do")
	public String userConfig(Model model,Long roleId,HttpServletRequest req,HttpServletResponse resp) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		model.addAttribute(PAGE_TITLE,"用户设置");
		model.addAttribute("roleId",roleId);
		if(roleId==null || roleId<=0L){
			model.addAttribute(ERROR_MSG,"没有该角色");
			return super.ERROR_PAGE;
		}
		IRoleService rs=(IRoleService) getService(RoleServiceImpl.class);
		RoleEntity ce=rs.getEntityById(roleId);
		if(ce==null){
			model.addAttribute(ERROR_MSG,"没有该角色");
			return super.ERROR_PAGE;
		}
		return "manage/role/userConfig";
	}
	@RequestMapping("Manage/Role/getRoleUserInfo.do")
	public  void getRoleUserInfo(Long roleId,Integer page,Integer rows,Integer displayRoleUserInfo,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		if(roleId==null || roleId<=0L){
			super.printMsg(resp, "-1", "-1", "没有该角色");
			return;
		}
		roleId=(roleId==null)?-1L:roleId;
		if(roleId==-1L){
			super.printMsg(resp, "-1", "-1", "参数缺失");
			return;
		}
		page=(page==null)?1:page;
		rows=(rows==null)?10:rows;
		displayRoleUserInfo=(displayRoleUserInfo==null)?0:displayRoleUserInfo;
		IUserRoleService urServ=(IUserRoleService) getService(UserRoleServiceImpl.class);
		List<UserRoleEntity> urList=urServ.getListByRoleId(roleId);
		IUserService uServ=(IUserService) getService(UserServiceImpl.class);
		List<ExtUserRoleEntity> extList=new ArrayList<ExtUserRoleEntity>();
		if(displayRoleUserInfo==1){
			if(urList!=null){
				for(UserRoleEntity u:urList){
					ExtUserRoleEntity ext=new ExtUserRoleEntity(u);
					UserEntity tmp=uServ.getEntityById(ext.getUserId());
					if(tmp!=null){
						ext.setUserName(tmp.getUserName());
						ext.setChecked(true);
					}
					extList.add(ext);
				}
			}
		}else{
			String siteHql="";
			if(SysUtil.getCurrentSiteId(req.getSession())!=-1L){
				siteHql="subSiteId="+SysUtil.getCurrentSiteId(req.getSession())+" and ";
			}
			List<UserEntity> allUserList=uServ.getList("from "+uServ.getTableName()+" where "+siteHql+" locked=false and state=99", null, "createTime desc", rows,rows*(page-1));
			for(UserEntity user:allUserList){
				ExtUserRoleEntity ext=new ExtUserRoleEntity(user);
				if(urList!=null){
					for(UserRoleEntity u:urList){
						if(u.getUserId().equals(user.getId())){
							ext.setChecked(true);
							break;
						} 
					} 
				}				
				extList.add(ext);
			}
		}
		super.sendJsonByList(resp, extList, Long.valueOf(extList.size()));
		
	}
	@RequestMapping("Manage/Role/doRoleUserInfo.do")
	public  void doRoleUserInfo(Long roleId,String userIds,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		if(roleId==null || StringUtils.isBlank(userIds)){
			super.printMsg(resp, "-1", "-1", "参数缺失");
			return;
		}
		IRoleService rs=(IRoleService) getService(RoleServiceImpl.class);
		RoleEntity ce=rs.getEntityById(roleId);
		if(ce==null){
			super.printMsg(resp, "-2","-2","没有该角色");
			return;
		}
		IUserRoleService urServ=(IUserRoleService) getService(UserRoleServiceImpl.class);
		urServ.clearRoleUser(roleId);
		if(userIds.trim().equals("-1")){
			
		}
		String[] ids=userIds.split(",");
		for(String id:ids){
			if(StringUtils.isNumeric(id)){
				Long uid=Long.valueOf(id.trim());
				UserRoleEntity t=new UserRoleEntity();
				t.setRoleId(roleId);
				t.setUserId(uid);
				urServ.saveEntity(t);
			}
		}
		super.printMsg(resp, "99", "99", "保存成功");
	}
	@RequestMapping("Manage/Role/saveRolePermissionConfig.do")
	public void saveRolePermissionConfig(Long roleId,String confIds,HttpServletRequest req,HttpServletResponse resp) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		if(roleId==null || roleId<=0L){
			super.printMsg(resp, "-1", "-1", "role参数错误");
			return;
		}
		if(!StringUtils.isBlank(confIds)){
			String[] sids=confIds.split(";");
			IRolePermissionService rpServ=(IRolePermissionService) getService(RolePermissionServiceImpl.class);
			rpServ.delRolePermission(roleId);
			for(String ids:sids){
				String[] t=ids.split(":");
				if(t.length==3){
					String funId=t[1];
					String modelId=t[0];
					String typeId=t[2];
					RolePermissionEntity re=new RolePermissionEntity();
					re.setRoleId(roleId);
					if(StringUtils.isNumeric(funId))
						re.setFunId(Long.valueOf(funId));
					if(StringUtils.isNumeric(modelId))
						re.setModelId(Long.valueOf(modelId));
					if(StringUtils.isNumeric(typeId))
						re.setTypeId(Integer.valueOf(typeId));
					if(re.getFunId()!=-1 && re.getModelId()!=null && re.getTypeId()!=-1){
						rpServ.saveEntity(re);
					}
				}
			}
			super.printMsg(resp, "99", "1", "保存成功");
		}else{
			super.printMsg(resp, "-2", "-2", "参数不足");
		}
	}
}
